import { plainToInstance } from "class-transformer";
import ResultHelper from "../routes/utils/ResultHelper";
import { EmailCodeEntity } from "../entities/EmailCodeEntity";
import EmailCodeDao from "../dao/EmailCodeDao";
import _ from "lodash";

import moment from "moment";
import { sendMail } from "../utils/emailHelper";

// enum EmailCodeStatus {
//   OVERTIME = "已过期",
//   USED_OR_NONE = "已使用",
// }

export default class EmailCodeService {
  /**
   * 创建邮箱验证码
   * @param email 邮箱地址
   * @param active 活动 类型
   * @returns
   */
  static async create(email: string, active: string = "验证邮箱") {
    if (!email) {
      return ResultHelper.error("请输入邮箱");
    }

    const EmailCode = plainToInstance(EmailCodeEntity, {
      email,
      code: _.random(100001, 999999),
    });
    const errs = await EmailCode.validateThie();

    if (errs.length > 0) {
      return ResultHelper.error(errs);
    }

    try {
      const result = await EmailCodeDao.create(EmailCode);
      if (result) {
        /* 数据库添加成功 */
        const sendMailResult = await sendMail(
          EmailCode.email,
          EmailCode.code,
          active
        );
        if (sendMailResult.code === 2000 /* 邮箱发送成功 */) {
          return ResultHelper.success({}, "发送成功");
        } else {
          return ResultHelper.error(sendMailResult.msg || "发送失败");
        }
      } else {
        return ResultHelper.error("发送失败");
      }
    } catch ({ message }) {
      return ResultHelper.error(message);
    }
  }

  /**
   *
   * @param email 邮箱
   * @param code 验证码
   * @returns
   */
  static async verify(email: string, code: string) {
    if (!email) {
      return ResultHelper.error("请输入邮箱");
    }

    if (!code) {
      return ResultHelper.error("请输入验证码");
    }

    const EmailCode = plainToInstance(EmailCodeEntity, {
      email,
      code,
      status: 0,
    });
    const errs = await EmailCode.validateThie();

    if (errs.length > 0) {
      return ResultHelper.error(errs);
    }

    try {
      const result = await EmailCodeDao.find(EmailCode);

      // return
      if (result) {
        // 表示存在 且 为使用状态，需要验证验证码是否过期

        const createTime = result?.createdAt;
        const nowTime = moment().format();
        const diffTime = moment(nowTime).diff(createTime, "minutes");
        if (diffTime < 5) {
          return ResultHelper.success({}, "验证成功");
        } else {
          return ResultHelper.error("验证码已过期");
        }
      } else {
        // 表示不存在 或者 已经使用
        return ResultHelper.error("验证码错误或已使用");
      }
    } catch ({ message }) {
      return ResultHelper.error(message);
    }
  }
}
